package com.tib.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tib.pojo.RecentNews;
import com.tib.pojo.SystemMessages;
import com.tib.service.RecentNewsService;
import com.tib.utils.JsonRequest;
import com.tib.utils.JsonResponse;
import com.tib.utils.PageResult;
import com.tib.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/recentNews")
@Api(value = "/recentNews" ,tags = "最新动态api")
public class RecentNewsController {
    @Autowired
    RecentNewsService recentNewsService;

    @ApiOperation("删除")
    @PostMapping("/delete")
    public JsonResponse delete(@RequestBody JsonRequest<?> jsonRequest){
        String id = jsonRequest.getParamAsString("id");
        if (recentNewsService.delete(id)==1){
            return JsonResponse.newOk("删除成功");
        }
        return JsonResponse.newError("删除失败");
    }

    @ApiOperation("增添")
    @PostMapping("/insert")
    public JsonResponse insert(@RequestBody JsonRequest<?> jsonRequest){
        RecentNews record = JSONObject.parseObject(JSON.toJSONString(jsonRequest.getData()),RecentNews.class);
        record.setId(StringUtil.getGuid32());
        if (recentNewsService.insert(record)==1){
            return JsonResponse.newOk("插入成功");
        }
        return JsonResponse.newError("插入失败");
    }

    @ApiOperation("按id查询")
    @PostMapping("/select")
    public JsonResponse select(@RequestBody JsonRequest<?> jsonRequest){
        Map map = JSONObject.parseObject(JSON.toJSONString(jsonRequest.getData()));
        if (map.containsKey("title")){
            map.put("newContent",map.get("title"));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Map> resMap = recentNewsService.select(map);
        for(Map map1:resMap){
            if (map1.containsKey("timestamp")){
                map1.put("timestamp",sdf.format(map1.get("timestamp")));
            }
            if (map1.containsKey("updatedTime")){
                map1.put("updatedTime",sdf.format(map1.get("updatedTime")));
            }
        }
        return JsonResponse.newOk(resMap);
    }

    @ApiOperation("修改")
    @PostMapping("/update")
    public JsonResponse update(@RequestBody JsonRequest<?> jsonRequest){
        Map map = JSONObject.parseObject(JSON.toJSONString(jsonRequest.getData()));
        if (map.containsKey("createdTime")){
            Date date = new Date((Long) map.get("createdTime"));
            map.put("createdTime",date);
        }
        if (recentNewsService.update(map)==1){
            return JsonResponse.newOk("修改成功");
        }
        return JsonResponse.newError("修改失败");
    }

}
